let {
    start_app,
    click_item,
    tts_report,
    set_volume,
    handleDateTime,
    get_my_seconds,
    get_my_hours,
    get_my_minutes
} = require('lib.js');


function main() {

    if (className("android.view.View").desc('美团买菜').exists()) {
        click_item('美团买菜', undefined, 'no_tip', 1)
    }

    device.keepScreenOn(3600 * 1000)

    // 点击购物车
    const clickShoppingcart = () => {
        var shopping_cart = id("img_shopping_cart").findOne();
        //获取其中心位置并点击
        click(shopping_cart.bounds().centerX(), shopping_cart.bounds().centerY());
    }

    // 点击结算
    const clickSettle = () => {
        sleep(150)
        className("android.view.View").depth(22).findOne().parent().click()
    }

    // 点击我知道了
    const clickKnow = () => {
        className("android.view.View").depth(16).findOne().parent().click()
    }
    //点击放弃机会
    const clickGiveup = () => {
        className("android.widget.TextView").text("放弃机会").findOne().parent().parent().click()
    }
    // 点击立刻支付
    const clickPay = () => {
        className("android.widget.TextView").text("立即支付").findOne().parent().click()
    }
    //拥堵繁忙
    const clickBusy = () => {
        try {
            className("android.view.View").depth(15).findOne().parent().click()
        } catch (error) {
            console.error("点击我知道了错误:" + error)
            sleep(50)
        }
    }
    //约满
    const clickFull = () => {
        className("android.widget.TextView").depth(15).findOne().parent().click()
    }

    const hasText = (text) => {
        return textStartsWith(text).exists() // 是否存在指定文本
    }


    //是否选中购物车
    const hasSelectedShoppingcart = () => {
        return id("img_shopping_cart").findOne().selected() // 是否选中
    }

    //提示
    const startTibs = () => {
        while (hasText('美团买菜-订单编号')) {
            tts_report("快付款")
            sleep(3000)
        }
    }

    const meituanMianMiPay = () => {

        if (id("btn-line").exists()) {
            tts_report("免密支付中")
            let btnLine = id("btn-line").findOne();
            //获取其中心位置并点击
            click(btnLine.bounds().centerX(), btnLine.bounds().centerY());
        }

        while (true) {
            if (hasText('支付成功')) {
                tts_report("支付完成")
                exit();
            }
        }
    }

    /**
     * 随机位置点
     * @param {起始值} start 
     * @param {结束值} end 
     * @returns 
     */
    const randomPointLoc = (start, end) => {
        len = end - start;
        loc = Math.floor(Math.random() * len) + start;
        return loc;
    }

    /**
     * 刷新
     */
    const slidingByLine = () => {
        try {
            log('刷新')
            // bottom X，Y 范围
            // bx = randomPointLoc(400, 700);
            // by = randomPointLoc(1880, 2000);
            // swipe(bx, by, 300, 2500, 300);
            sleep(100)
            if (recents()) {
                sleep(200)
                app.launch('com.sankuai.meituan')
            }
        } catch (error) {
            console.error("刷新错误:" + error);
            sleep(50)
            app.launch('com.sankuai.meituan')
        }


    }

    console.show()
    //选中购物车
    var thread1 = threads.start(function () {
        while (true) {
            if (!hasSelectedShoppingcart()) {
                clickShoppingcart();
                log('购物车已选中')
                thread1.interrupt();
            }
            sleep(500)
        }
    });

    //选中我知道
    var thread2 = threads.start(function () {
        while (true) {
            try {
                if (className("android.view.View").depth(15).exists() && !className("android.widget.FrameLayout").depth(14).exists()) {
                    console.log("我知道了")
                    clickBusy();
                }
                sleep(50)

            } catch (error) {
                console.error("选中我知道了错误:" + error)
            }
        }
    });


    let retryNum = 0;
    let retryText = '无';

    const retryNumAdd = (text) => {
        if (retryText == text) {
            retryNum++;
        }
        retryText = text;

    }

    var i = 0;
    const start = () => {
        try {
            i++;
            console.log('重试:' + i)
            if (retryNum >= 2 && !className("android.widget.TextView").text("提交订单").exists()) {

                console.log("下滑" + retryNum)
                retryNum = 1;
                slidingByLine()
                sleep(50)
                start()
            } else if (hasText('立即支付')) {
                console.log('立即支付')
                try {
                    clickPay()
                    if (hasText('我知道了')) {
                        clickBusy();
                    }
                } catch (error) {
                    console.error(error)
                } finally {
                    sleep(50)
                    start()
                }
            } else if (hasText('美团买菜-订单编号')) {
                set_volume(80)
                tts_report("抢到了")
                console.log('美团买菜抢到了')
                meituanMianMiPay();
                startTibs();

            } else if (hasText('放弃机会')) {
                retryNumAdd('放弃机会')
                console.log('放弃机会')
                clickGiveup()
                sleep(50)
                start()
            } else if (hasText('前方拥堵')) {
                try {
                    retryNumAdd('前方拥堵')
                    console.log('前方拥堵')

                    if (hasText('我知道了')) {
                        clickBusy();
                    } else {
                        try {
                            console.log("前方拥堵:结算")
                            clickSettle()
                        } catch (e) {
                            console.error("点击结算异常：:" + error)
                        } finally {
                            sleep(80)
                            start()
                        }
                    }
                } catch (error) {
                    console.error(error)
                } finally {
                    sleep(100)
                    start()
                }
            } else if (hasText('当前不在可下单时段') || hasText('很抱歉')) {
                retryNumAdd('当前不在可下单时段')
                console.log('当前不在可下单时段')
                clickKnow()
                sleep(50)
                start()
            }
            else if (hasText('配送运力已约满')) {
                retryNumAdd('配送运力已约满')
                console.log('已约满')
                clickFull()
                sleep(50)
                start()
            } else if (hasText('订单已约满')) {
                retryNumAdd('订单已约满')
                console.log('已约满')
                clickFull()
                sleep(50)
                start()
            } else if (hasText("结算")) {
                retryNumAdd('结算')
                console.log("结算")
                try {
                    clickSettle()
                } catch (e) {
                    console.error("点击结算异常：:" + error)
                } finally {
                    sleep(80)
                    start()
                }
            }
            else {
                console.log('请选择购物车')
                retryNumAdd('请选择购物车')

                sleep(100)
                start()
            }
        } catch (error) {
            console.error("start任务异常:" + error)
            sleep(50)
            start()
        }
    }

    let needSyncTime = true
    var lock = threads.lock()
    var timeNum = 0
    let serverTimeOffset = 0
    let autoSync = 20;
    threads.start(function () {
        while (true) {
            if (needSyncTime) {
                let start = new Date().getTime()
                needSyncTime = false;
                http.get('http://api.m.taobao.com/rest/api3.do?api=mtop.common.getTimestamp', {}, (res, err) => {
                    if (err) {
                        console.error('请求异常', err)
                        return
                    }
                    if (res.body) {
                        lock.lock();
                        try {
                            let data = JSON.parse(res.body.string())
                            console.verbose('result: ' + JSON.stringify(data))
                            let serverTimestamp = parseInt(data.data.t)
                            let localTimestamp = new Date().getTime()
                            let cost = localTimestamp - start
                            // 计算本机和服务端时间差 服务端时间加上请求所消耗时间的一半 减去当前本机时间
                            serverTimeOffset = serverTimestamp + (cost / 2) - localTimestamp
                        } catch (e) {
                            console.error('执行异常:' + e)
                        } finally {
                            lock.unlock();
                        }
                    }
                })
            }
        }
    });



    const startTime = () => {
        try {
            let d = handleDateTime(new Date().getTime() + serverTimeOffset, "hh:MM:ss");
            let h = get_my_hours(d);
            let m = get_my_minutes(d);
            let s = get_my_seconds(d);
            if (h > 5) {
                start()
            } else {
                if (timeNum >= autoSync) {
                    timeNum = 0;
                    needSyncTime = true;
                }
                if (h == 5 && m == 58) {
                    autoSync = 3;
                }
                if (h == 5 && m == 59 && s == 57) {
                    console.log("执行开始");
                    start()
                }
                console.log(d)
                let ss = (((5 - h) * 60) + ((59 - m))) * 60 + (57 - s)
                console.log("倒计时:" + ss + "秒")
                timeNum++;
                sleep(800)
                startTime();
            }

        } catch (error) {
            console.error("startTime任务异常:" + error)
            sleep(50)
            start()
        }
    }
    startTime();

}

start_app(main, '美团', '美团买菜', false)